<template>
	<div>
		<el-container class="div-style">

			<el-main>
				<div style="width: 100%;height: 76%;padding-top: 10px;overflow-y: auto;">
					<!-- 普通点名 -->
					<div class="div-style-content" :style="{'font-size': settings.fontSize+'px'}" v-if="rollBook.type == 0">
						{{rollBook.msg}}
					</div>

					<!-- 动画点名 -->
					<el-scrollbar height="100%" :style="{'font-size': settings.fontSize+'px'}" v-if="rollBook.type == 1">
						<div v-for="item in rollBook.arrs" style=" display: inline-block;">
							<div v-if="item.status == '0'" class="name-border" style="background-color: lightblue;">{{item.name}}
							</div>
							<div v-else class="name-border">{{item.name}}</div>
						</div>
					</el-scrollbar>

					<el-scrollbar height="100%" :style="{'font-size': settings.fontSize+'px'}" v-if="rollBook.type == 2">
						<div v-for="(item,index) in rollBook.arrs" @click="clickCard(index)"
							style="border-radius: 5px;border: 1px solid antiquewhite;display: inline-block;animation: issueCard1 0.2s;margin: 3px 3px;background-color: antiquewhite;">
							<!-- <view v-if="item.status == '0'" class="name-border" style="background-color: lightblue;opacity: 0;">{{item.name}}</view> -->
							<div :class="['name-border1', {'content-view-card': item.status}]" v-if="item.status">{{item.name}}</div>
							<div :class="['name-border1', {'content-view-card': item.status}]" v-else></div>
						</div>
					</el-scrollbar>

				</div>
				<div style="height: 10%;text-align: center;">
					<div>
						<el-button type="primary" round style="width: 45%;" v-if="!settings.randomNameShow"
							@click="clickRandomName">开始点名</el-button>
					</div>
					<div @click="bindclear">
						<el-button type="primary" round loading style="width: 45%;"
							v-if="settings.randomNameShow">点名中...</el-button>
					</div>
				</div>
			</el-main>
		</el-container>

		<!-- 设置按钮 -->
		<div style="display: inline-block;position: absolute;right: 30px;bottom: 10%;color: white;">
			<span class="span-style" @click="settings.popupShow =true">
				<Setting style="width: 1em; height: 1em; margin-right: 8px" />
			</span>
			<!-- <span class="span-style" ><Document style="width: 1em; height: 1em; margin-right: 8px" /></span> -->
		</div>

		<el-drawer v-model="settings.popupShow" direction="rtl" size="40%" @close="closeDrawer">
			<template #header>
				<h4>点名设置</h4>
			</template>
			<template #default>
				<div style="height: 352px;">
					<popupContent marginTop="38" content='字体大小' display="block">
						<el-slider v-model="settings.fontSize" :min="10" :max="190" />
					</popupContent>
					<popupContent content='背景音乐'>
						<div style="display: flex;align-items: center;">
							<el-switch v-model="settings.backgroundAudioSwitchShow" class="mt-2" inline-prompt />
							<el-upload class="upload-demo" :action="fileUrl" :data="fileData" name="images" :limit="1"
								style="display: flex;" :before-upload="beforeAvatarUpload" :on-success="fileOnSuccess"
								:show-file-list="false">
								<el-tooltip class="box-item" effect="dark" content="先下载mp3格式音频文件，在选择并上传。" placement="top-start">
									<div class="view-text-decoration-style">替换背景音乐</div>
								</el-tooltip>

							</el-upload>

						</div>
					</popupContent>
					<popupContent content='点名方式'>
						<div style="display: flex;align-items: center;">
							<div class="view-background weui-agree__link buttonName" v-if="rollBook.type==0"
								style="margin-left: 0px;">普通</div>
							<div class="view-background weui-agree__link" v-else style="margin-left: 0px;" @click="rollBookType(0)">普通
							</div>

							<div class="view-background weui-agree__link buttonName" v-if="rollBook.type==1"
								style="margin-left: 0px;">动画</div>
							<div class="view-background weui-agree__link" v-else style="margin-left: 0px;" @click="rollBookType(1)">动画
							</div>

							<div class="view-background weui-agree__link buttonName" v-if="rollBook.type==2"
								style="margin-left: 0px;">翻牌</div>
							<div class="view-background weui-agree__link" v-else style="margin-left: 0px;" @click="rollBookType(2)">翻牌
							</div>
						</div>
					</popupContent>
					<popupContent content='重复点名'>
						<div style="">
							<el-switch v-model="settings.repetitionStudentName" class="mt-2" inline-prompt />
						</div>
					</popupContent>
					<popupContent content='批量点名'>
						<div style="">
							<el-switch v-model="settings.batchStudentNameShow" class="mt-2" inline-prompt />
						</div>
					</popupContent>
					<popupContent content='自动停止'>
						<div style="">
							<el-switch v-model="settings.autoStop" class="mt-2" inline-prompt />
						</div>
					</popupContent>
					<popupContent content='语音播放'>
						<div style="display: flex;align-items: center;">
							<el-switch v-model="settings.audioPlayShow" class="mt-2" inline-prompt />
							<div class="view-text-style">
								剩余次数：<el-badge :value="settings.audioNumber" class="item"></el-badge>

								<el-tooltip class="box-item" effect="dark" content="点击修改语音设置" placement="top-start">
									<div class="view-text-decoration-style" style="margin-top: 4px;" @click="openAudioList">
										<Setting style="width: 1.5em; height: 1.5m; margin-right: 8px" />
									</div>
								</el-tooltip>

							</div>
						</div>
					</popupContent>
				</div>
			</template>
		</el-drawer>

		<audio-list v-if="audioListDialogVisible" ref="audioList"></audio-list>

		<audio controls="controls" hidden :src="settings.audioUrl" ref="audio"></audio>
		<audio controls hidden ref="audio1">
			<source :src="music" type="audio/mpeg">
		</audio>
	</div>
</template>

<script>
	var that, clearnumber, timesetInterval;
	var arrs = new Array();
	var repetitionArrs = new Array();
	var random = -1;

	import {
		useMouse
	} from '@/utils/index.js'
	import popupContent from '@/components/popupContent.vue'
	import {
		Check,
		Close
	} from '@element-plus/icons-vue'
	import AudioList from './AudioList.vue'
	import axios from "axios"
	import {
		hintMessage
	} from '../../../utils';
	export default {
		data() {
			return {
				music: '',
				audioListDialogVisible: false, //语音弹窗
				fileUrl: '',
				fileData: {
					type: "23",
					openId: ''
				},
				Check: Check,
				Close: Close,
				title: 'Hello',
				rollBook: { //点名相关
					notice: '关注“上课轻松点名”公众号，回复“教程”，获取使用教程。',
					classArray: [], //班级列表
					classIndex: 0, //班级选中下标
					idarr: [],
					classPickerShow: false, //选择班级弹窗显示
					classStudentArray: [], //班级对应学生列表
					msg: '', //点名内容
					arrs: [], //批量点名数组
					type: 0, //0:普通点名 1动画点名
				},
				settings: { //设置状态
					autoStop: false,
					audioUrl: '',
					fontSize: 35, //字体大小设置
					randomNameShow: false, //随机按钮开启状态
					popupShow: false, //设置功能弹窗状态
					backgroundAudioSwitchShow: false, //背景音乐开关
					batchStudentNameShow: false, //批量点名开关
					batchStudentNumber: 1, //批量点名人数
					modalShow: false, //批量点名人数填写弹窗
					repetitionStudentName: true, //重复点名
					audioPlayShow: false, //语音播放开关
					audioNumber: 0, //语音次数
					audioSetting: { //语音设置
						voice: 'zh-CN-XiaoxiaoNeural', //发音人
						volume: 50, //音量
						speech_rate: 0, //语速
						pitch_rate: 0, //语调
					},
					saveFile: '', //语音相关
					saveFd: '', //语音相关
					tts: '',
					ttsStart: false, //合成语音状态
				}
			};
		},
		watch: {
			'settings.batchStudentNameShow'() {
				//开启
				if (that.settings.batchStudentNameShow) {
					that.promptMessage("请输入批量点名的人数", (value) => {
						that.settings.batchStudentNumber = value || 1;
					});
				} else {
					//关闭
					that.settings.batchStudentNumber = 1;
				}
			},
			'settings.repetitionStudentName'() {
				//开启
				if (!that.settings.repetitionStudentName) {
					repetitionArrs = [];
				}
			}
		},
		setup() {
			return useMouse();
		},
		mounted() {
			that = this;
			that.settings.audioUrl = that.$store.state.pyurl + '/pub/image/audio/music.mp3';
			that.fileUrl = that.$store.state.pyurl + '/file/find';
			that.fileData.openId = that.$store.state.$userInfo.id;

			//背景音乐
			that.uploadAudio();
			that.getData();
		},
		methods: {
			async getData() {
				const data = await that.$asyncHttpConfig({
					url: '/classname/selectAudioNumber',
					data: {
						unionid: that.$store.state.$userInfo.id
					}
				})

				this.settings.audioNumber = data.audioNumber;
			},
			//关闭抽屉弹窗
			closeDrawer() {
				that.settings.popupShow = false;
				// that.settings.batchStudentNameShow =false;

				// localStorage.setItem("weixin_settings",JSON.stringify(that.settings))
			},
			//跳转声音设置
			openAudioList() {
				that.audioListDialogVisible = true;
				that.$nextTick(() => {
					that.$refs["audioList"].dialogVisible = true;
				})
			},
			//切换点名方式
			rollBookType(type) {
				that.rollBook.type = type;
				that.rollBook.arrs = [];
				repetitionArrs = [];
				if (type == 0) {
					that.settings.fontSize = 50;
				} else {
					that.settings.fontSize = 16;
				}
			},
			//文件上传成功
			fileOnSuccess(response) {
				console.log(response)
				// if(res.statusCode == 200){
				// 	var muLu="/etc/docker/data/python";
				// 	var url=that.$store.state.pyurl+res.data.substring(muLu.length);
				// 	console.log(url)

				// 	that.settings.audioUrl=url;

				// 	wx.setStorage({
				// 		key:"audio",
				// 		data:url
				// 	})
				// 	that.hintMessage('上传成功')
				// }else{
				// 	that.hintMessage('上传文件失败，请重试')
				// }
			},
			//上传之前的前缀
			beforeAvatarUpload(rawFile) {
				if (rawFile.type !== 'audio/mpeg') {
					that.hintMessage('请选择mp3格式文件')
					return false
				}

				return true
			},
			//点击翻牌
			clickCard(index) {
				that.rollBook.arrs[index].status = true;
				var content = that.rollBook.arrs[index].name;


				var {
					audioPlayShow,
					audioNumber
				} = that.settings;
				var {
					idarr,
					classIndex
				} = that.rollBook;

				//语音合成
				console.log(audioPlayShow + " " + audioNumber);
				if (audioPlayShow && audioNumber > 0) {
					that.onTtsStart(content);
				} else if (audioPlayShow && audioNumber <= 0) {
					that.hintMessage('语音次数不足，请联系客服')
				}

				//记录点名信息
				if (content != undefined) {

					//
					var dataForm = {
						openId: that.$store.state.$userInfo.id,
						classNameId: idarr[classIndex],
						userName: content,
					}

					const res = that.$asyncHttpJson('/randomNameController/save', dataForm);
					//这里只需要传入不同的接口地址就可以
				}

			},
			//开启随机点名
			async clickRandomName() {
				var {
					idarr,
					classIndex,
					classArray,
					type
				} = that.rollBook;
				let {
					backgroundAudioSwitchShow
				} = that.settings;

				if (!that.$store.state.classNameId) {
					return that.warningMessage("请先选择或添加班级")
				}

				//获取班级信息
				var dataForm = {
					openid: that.$store.state.$userInfo.id,
					classnameid: that.$store.state.classNameId,
				}
				const data = await that.$asyncHttp('/student/queryById', dataForm)
				that.rollBook.classStudentArray = data.studentList;

				if (data.studentList.length == 0) {
					that.confirmMessage("暂未添加学生,去添加？", () => {
						that.$router.push("/addSchool?schoolid=" + that.$store.state.classNameId)
						that.$store.state.activeIndex = "2";
					})
					return;
				}

				//显示停止按钮
				that.settings.randomNameShow = true;

				if (backgroundAudioSwitchShow) {
					that.$refs.audio.currentTime = 0; //从头开始播放
					that.$refs.audio.src = that.settings.audioUrl
					that.$refs.audio.autoplay = true;
					that.$refs.audio.loop = true;
					that.$refs.audio.play(); //播放
					that.hintMessage('提示：背景音乐开始播放');
				}

				arrs = new Array();
				//普通单个点名 或者 批量点名
				if (type == 0) {


					for (var i in data.studentList) {
						var studentName = data.studentList[i].studnetName;
						//开启不重复
						if (!that.settings.repetitionStudentName) {
							if (repetitionArrs.length == data.studentList.length) {
								repetitionArrs = [];
							}
							var index = repetitionArrs.findIndex(function(element) {
								return element == studentName;
							})

							if (index != -1) {
								continue;
							}
						}
						arrs.push(studentName);
					}


					clearInterval(clearnumber);
					clearnumber = setInterval(function() {
						arrs.sort(function() {
							return 0.5 - Math.random()
						});
						//循环执行代码

						random = Math.floor(Math.random() * arrs.length);
						that.rollBook.msg = arrs[random];

					}, 70);

					//定时停止
					that.timesetInterval();
				} else if (type == 1) {
					//动画点名
					for (var i = 0; i < data.studentList.length; i++) {

						var studentName = data.studentList[i].studnetName;
						//开启不重复
						if (!that.settings.repetitionStudentName) {

							if (repetitionArrs.length == data.studentList.length) {
								repetitionArrs = [];
							}
							var index = repetitionArrs.findIndex(function(element) {
								return element == studentName;
							})
							if (index != -1) {
								continue;
							}
						}
						arrs.push({
							"name": studentName,
							"status": '1'
						});
					}

					that.rollBook.arrs = arrs;


					//随机名称
					clearInterval(clearnumber);
					clearnumber = setInterval(function() {
						//重置值
						that.rollBook.arrs.forEach(function(value, index) {
							value.status = '1'
						});

						var random = Math.floor(Math.random() * that.rollBook.arrs.length);
						that.rollBook.arrs[random].status = '0';

						that.rollBook.msg = arrs[random].name;
					}, 70);

					//定时停止
					that.timesetInterval();
				} else if (type == 2) {
					//翻牌
					that.rollBook.arrs = [];
					let i = 0;
					let studentList = data.studentList;
					studentList.sort(function() {
						return 0.5 - Math.random()
					});

					clearnumber = setInterval(function() {

						if (i < studentList.length) {

							that.rollBook.arrs.push({
								"name": studentList[i].studnetName,
								"status": false
							});
							i++;
						} else {
							clearInterval(clearnumber);
							that.settings.randomNameShow = false;
						}
					}, 100);
				}

			},
			//定时停止
			timesetInterval() {
				if (!that.settings.autoStop) {
					return;
				}

				//定时停止
				let time = 5;
				timesetInterval = setInterval(function() {

					if (time <= 0) {
						clearInterval(timesetInterval);
						that.bindclear(); //结束点名
						return;
					}
					that.hintMessage(time + "秒后停止");
					time--;

				}, 1000);
			},
			//停止点名
			bindclear() {
				// innerAudioContext.stop();
				that.$refs.audio.pause(); //停止
				clearInterval(clearnumber);
				clearInterval(timesetInterval);

				let {
					msg,
					type,
					idarr,
					classIndex
				} = that.rollBook;
				let {
					batchStudentNameShow,
					batchStudentNumber,
					audioPlayShow,
					audioNumber
				} = that.settings;

				if (type == '2') {
					return;
				}

				//普通点名
				var content = "";
				if (msg != "") {
					content = msg;
				}

				//批量点名
				if (batchStudentNameShow) {
					var arrays = new Array();
					for (const key in arrs) {
						arrays.push(arrs[key]);
					}

					//获取是否方块 批量点名
					if (type != 0) {
						//重置值
						arrays = new Array();
						arrs.forEach(function(value, index) {
							value.status = '1';
							arrays.push(value);
						});
					}

					//随机获取名称
					var temp = that.randomManyName(arrays, batchStudentNumber);
					var text = "";

					//普通批量点名
					if (type == 0) {
						for (const key in temp) {
							text += temp[key] + ",";
							repetitionArrs.push(temp[key]);
						}
					} else {
						//是方块 动画点名
						for (const key in temp) {
							text += temp[key].name + ",";
							repetitionArrs.push(temp[key].name);
						}

						arrs.forEach(function(value, index) {
							var index = temp.findIndex(function(element) {
								return element.name == value.name;
							})
							if (index != -1) {
								value.status = '0';
							}
						});

						that.rollBook.arrs = arrs;
					}

					//普通批量点名
					if (type == 0) {
						that.confirmMessage(text);
					}

					that.rollBook.msg = '';

				} else {
					//
					repetitionArrs.push(msg);
				}

				that.settings.randomNameShow = false;

				//语音合成
				console.log(audioPlayShow + " " + audioNumber);
				if (audioPlayShow && audioNumber > 0) {
					that.onTtsStart(content);
				} else if (audioPlayShow && audioNumber <= 0) {
					that.hintMessage('语音次数不足，请联系客服')
				}

				//记录点名信息
				if (content != undefined) {

					//
					var dataForm = {
						openId: that.$store.state.$userInfo.id,
						classNameId: idarr[classIndex],
						userName: content,
					}

					that.$asyncHttpJson('/randomNameController/save', dataForm);
					//这里只需要传入不同的接口地址就可以

				}
			},
			//随机名称
			randomManyName(arr, number) {
				var temp = new Array(); //temp存放生成的随机数组
				var count = arr.length;

				for (var i = 0; i < count; i++) {
					if (temp.length == number) {
						break;
					}
					var num = Math.floor(Math.random() * arr.length); //生成随机数num
					temp.push(arr[num]); //获取arr[num]并放入temp
					arr.splice(num, 1);

				}
				return temp;
			},
			//选择班级
			selectClassConfirm(i) {
				that.rollBook.classIndex = i;
				that.rollBook.arrs = [];
				repetitionArrs = []; //重置不重复列表

				let {
					classArray
				} = that.rollBook;
				clearInterval(clearnumber);
				clearInterval(timesetInterval);


				that.rollBook.msg = "";
				that.settings.randomNameShow = false;
				arrs = [];
				// innerAudioContext.stop();
			},
			textCreateAudio(content, voice) {
				let fileName = that.$store.state.$userInfo.id + new Date().getTime() + ".mp3";
				that.settings.ttsStart = false
				axios({
					url: that.$store.state.pyurl + '/file/find',
					method: 'POST',
					data: {
						type: 37,
						text: content,
						voice: voice,
						fileName: fileName
					},
					headers: {
						'content-type': 'application/x-www-form-urlencoded' // 默认值
					},
				}).then((res) => {
					console.log(res)
					if (!res.data) {
						return that.hintMessage("合成失败，请重试")
					}

					that.$refs.audio.pause();

					that.$refs.audio.src = res.data;
					that.$refs.audio.autoplay = false;
					that.$refs.audio.loop = false;
					that.$refs.audio.play(); //播放

					//非会员
					if (!that.$store.state.member) {
						axios({
							url: that.$store.state.url +
								'/randomNameController/updateUserAudioNumber',
							method: 'GET',
							data: {
								openId: that.$store.state.$userInfo.id
							},
							headers: {
								'content-type': 'application/x-www-form-urlencoded' // 默认值
							},
						}).then((res) => {
							that.settings.audioNumber = res.data.audioNumber
						})
					}
				})
			},
			//语音合成
			onTtsStart: async function(content) {

				if (that.$store.state.settings.voice.indexOf("zh-") != -1) {
					that.textCreateAudio(content, that.$store.state.settings.voice);
					return;
				}

				let dataForm = {
					openId: that.$store.state.$userInfo.id,
					text: content,
					voice: that.$store.state.settings.voice,
					volume: that.$store.state.settings.volume,
					speech_rate: that.$store.state.settings.speech_rate,
					pitch_rate: that.$store.state.settings.pitch_rate
				}

				that.$http.post('/user/createAudio', dataForm, {
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					responseType: 'blob'
				}).then(async(res) => {

					const myBlob = new window.Blob([res.data], {
						type: 'audio/mpeg'
					})
					const qrUrl = window.URL.createObjectURL(myBlob)
					that.$refs.audio.pause();

					that.$refs.audio.src = qrUrl;
					that.$refs.audio.autoplay = false;
					that.$refs.audio.loop = false;
					that.$refs.audio.play(); //播放
					
					await that.getData();
				})

				
			},
			//背景音乐地址
			uploadAudio() {

				axios({
					url: that.$store.state.pyurl + '/file/find',
					method: 'POST',
					data: {
						openId: that.$store.state.$userInfo.id,
						type: '24'
					},
					headers: {
						'content-type': 'application/x-www-form-urlencoded' // 默认值
					},
				}).then((res) => {
					console.log(res)
					if (res.status == 200) {
						if (res.data == 1) {
							that.settings.audioUrl = that.$store.state.pyurl + '/pub/image/audio/' + that.$store.state.$userInfo
								.id + ".mp3"
							console.log(that.settings.audioUrl)
						}

					}
				})
			},
		},
		components: {
			popupContent,
			AudioList
		}
	}
</script>

<style>
	.name-border {
		display: inline-block;
		border: 1px solid;
		padding: 3px 6px;
		border-radius: 5px;
		text-align: center;
		min-width: 115px;
	}

	.name-border1 {
		display: inline-block;
		border: 1px solid;
		padding: 3px 6px;
		border-radius: 5px;
		text-align: center;
		min-width: 115px;
		opacity: 0;
	}

	.div-style-class {
		border-bottom: 1px solid var(--el-menu-border-color);
		height: 50px;
		display: flex;
		align-items: flex-end;
		margin-left: 10px;
		padding-bottom: 5px;
		color: #3c3c3cb3;
		font-weight: 600;
		background: white;
		font-size: 12px;
	}

	.content-view-card {

		opacity: 1;
		animation: contxtRotate 0.5s;
	}

	.span-style {
		width: 30px;
		height: 30px;
		border-radius: 50%;
		background-color: #f89898;
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}

	.view-text-decoration-style {
		color: rgb(41, 121, 255);
		font-size: 15px;
		text-decoration: underline rgb(41, 121, 255);
		margin-left: 26px;
	}

	.weui-agree__link {
		display: inline-block;
		color: #576B95;
		border: 1px solid;
		border-radius: 7px;
		padding: 3px 5px;
		margin-left: 167rpx;
	}

	.buttonName {
		text-align: left;
		margin-left: 0px;
		background-color: #DEDEDE;
		color: #FFFFFF !important;
	}

	.view-text-style {
		display: flex;
		align-items: center;
		font-size: 12px;
		color: #909399;
		margin-left: 26px;
	}
</style>